package com.region.http.client.request;

import com.region.http.client.model.MultiFileTransferMeta;
import com.region.http.client.model.RequestParameter;

import java.io.File;
import java.io.InputStream;
import java.util.Collection;
import java.util.Map;

/**
 * The Share method abstract class
 *
 * @author liujieyu
 * @date 2024/9/30 16:28
 * @desciption
 */
public abstract class AbstractTemplateHttpExecutor implements HttpExecutor {

    /**
     * Wrap path parameters to url for the specified ContentType.X_WWW_FORM_URLENCODED
     *
     * @param form
     * @param url
     * @return
     */
    protected String processUrl(Map<String, Object> form, String url) {
        StringBuilder stringBuilder = null;
        if (form != null && !form.isEmpty()) {
            stringBuilder = new StringBuilder();
            for (Map.Entry<String, Object> entry : form.entrySet()) {
                String name = entry.getKey();
                String value = String.valueOf(entry.getValue());
                if (stringBuilder.length() != 0) {
                    stringBuilder.append("&");
                }
                stringBuilder.append(name);
                stringBuilder.append("=");
                stringBuilder.append(value);
            }
        }
        if (null == stringBuilder) {
            return url;
        } else {
            String params = stringBuilder.toString();
            return url + "?" + params;
        }
    }

    /**
     * exists file type or the array of byte, if exists than true else false
     *
     * @param parameter
     * @return
     */
    protected boolean existsFileType(RequestParameter parameter) {
        Map<String, Object> form = parameter.getForm();
        if (form != null && !form.isEmpty()) {
            Collection<Object> values = form.values();
            for (Object value : values) {
                if (value instanceof File || value instanceof byte[] || value instanceof InputStream || value instanceof MultiFileTransferMeta) {
                    return true;
                }
            }
        }
        return false;
    }

}
